package service

import (
	"fmt"
	"shop/common/log"
	"shop/config"
	"shop/dao"
	"shop/utils/result"
	"shop/utils/wxpay"
)

// OrderPay 订单支付：微信小程序支付
func OrderPay(shopId int, userId int64, orderNo, payType string) *result.Result {
	order := dao.GetOrderByOrderNoAndUserId(orderNo, userId)
	if order == nil || order.OrderNo == "" {
		return result.Fail("order not exists")
	}

	merchant := config.GetMerchantConfByShopId(shopId)
	if merchant == nil || merchant.ShopId == 0 {
		return result.Fail("商家不存在或已下线")
	}

	params := &wxpay.UnifiedOrderParams{
		OutTradeNo: orderNo,
		TotalFee:   order.TotalPrice,
		Body:       fmt.Sprintf("shop%d-%s", merchant.ShopId, orderNo),
		TradeType:  payType,
		Openid:     GetUserInfo(userId).Username,
		NotifyUrl:  config.WeixinPayNotify,
	}
	cli := wxpay.NewClient(merchant.WxMpAppId, merchant.WxPayMchId, merchant.WxPayApiKey)
	payData, err := cli.UnifiedOrder(params)
	if err != nil {
		log.Errorf("微信下单失败，err: %+v", err)
		return result.Fail(err.Error())
	}
	return result.Ok(payData)
}
